package data

import (
	"github.com/go-kratos/kratos/v2/log"
	_ "github.com/go-sql-driver/mysql"
	"hello-kratos/kratos-server/internal/conf"
	"hello-kratos/kratos-server/internal/data/ent"
)

type Mysql struct {
	// https://entgo.io/docs/crud
	client *ent.Client
	l      *log.Helper
}

func NewMysql(data *conf.Data, logger log.Logger) (*Mysql, func(), error) {
	client, err := ent.Open("mysql", data.Mysql.Dsn)
	if err != nil {
		return nil, nil, err
	}
	l := log.NewHelper(logger)
	cleanup := func() {
		l.Info("closing mysql connection")
		if err = client.Close(); err != nil {
			l.Errorf("close mysql connection error: %v", err)
		}
	}
	return &Mysql{
		client: client,
		l:      l,
	}, cleanup, nil
}
